package com.acme.bankapp.service.bank;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.domain.bank.Client;
import com.acme.bankapp.domain.bank.Gender;
import com.acme.bankapp.domain.exceptions.ClientExistsException;
import com.acme.bankapp.domain.exceptions.ClientFeedDataException;

public class BankDataLoaderService {
	
	private String fileName;
	private List<String> fileLines;
	private BankService bankService;
	private Bank bank;

	
	public BankDataLoaderService(String fn, BankService bs, Bank bk) throws IOException{
		this.fileName = fn;
		this.fileLines = this.getLinesFromFile(fileName);
		this.bankService = bs;
		this.bank = bk;
	}
	

	
	public void parseFeed() throws ClientExistsException{
		StringTokenizer st;
		Map<String, String> map;
		Client cl;
		for (String line: fileLines){
			st = new StringTokenizer(line, ";");
			map = parseOneLine(st);
			try{
				cl = Client.createClient(map);
				this.bankService.addClient(this.bank, cl);
			}catch(ClientFeedDataException cle){}
		}
	}
	
	private Map<String, String> parseOneLine(StringTokenizer st){
		Map<String, String> map = new HashMap<String, String>();
		String param;
		List<String> oneParamValue = new ArrayList<String>();
		while (st.hasMoreTokens()){
			param = st.nextToken();
			oneParamValue.addAll(Arrays.asList(param.split("=")));
			if (oneParamValue.size() > 1){
				map.put(oneParamValue.get(0), oneParamValue.get(1));
			}
			oneParamValue.clear();
		}
		return map;
	}
	
	private List<String> getLinesFromFile(String fileName) throws IOException{
		File file = new File(fileName);
        List <String> lines = new ArrayList<String>();
        if (file.exists() && file.isFile() && file.canRead()) {
            FileReader fileReader = new FileReader(file);
            LineNumberReader lineNumberReader = new LineNumberReader(fileReader);
            String currentLine;;
            while ( (currentLine = lineNumberReader.readLine()) != null ){
            	lines.add(currentLine);
            }
            lineNumberReader.close();
        }
        return lines;
	}
}
